#include "../include/threadPool.h"
#include <mysql/mysql.h>
int isInTable(MYSQL *mysql,const char *userName){//查看用户是否存在
    char query[1024];//定义字符数组用于SQL查询语句
    sprintf(query,"select count(*) from user where username='%s'",userName);
    if(mysql_query(mysql,query)!=0){//执行SQL查询语句
        fprintf(stderr,"查询错误：%s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *result=mysql_store_result(mysql);//获取查询结果集
    if(result==NULL){
        fprintf(stderr,"结果集错误：%s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_ROW row=mysql_fetch_row(result);
    int count=row?atoi(row[0]):0;
    mysql_free_result(result);//释放结果集
    //printf("%d\n",count);
    return count>0?0:-1;
}
int checkPassword(MYSQL *mysql,const char *userName,const char *password){//查用户密码是否正确
    char query[1024];
    sprintf(query,"select password from user where username='%s' and is_deleted = 0;",userName);
    if(mysql_query(mysql,query)!=0){
        fprintf(stderr,"查询失败：%s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *result=mysql_store_result(mysql);
    if(result==NULL){
        fprintf(stderr,"结果错误:%s\n",mysql_error(mysql));
        return -1;
    }
    int match=0;
    MYSQL_ROW row=mysql_fetch_row(result);
    if(row && row[0]){
        match=strcmp(password,row[0]);
    }
    if(match == 0){
        printf("密码正确!\n");
        mysql_free_result(result);
        return 0;
    }else{
        printf("密码错误!\n");
        mysql_free_result(result);
        return -1;
    }
}
int addUser(MYSQL *mysql,const char *userName,const char *password,const char *salt){//添加一个用户条目
    char query[1024];
    sprintf(query,"insert into user (username,salt,password,is_deleted) values ('%s','%s','%s',%d);",userName,salt,password,0);
    if(mysql_query(mysql,query)!=0){
        fprintf(stderr,"mysql_query:%s\n",mysql_error(mysql));
        return -1;
    }
    printf("用户添加成功！\n");
    return 0;
}

int checkSalt(MYSQL *mysql,const char *userName,char *salt){
    char query[1024];
    sprintf(query,"select salt from user where username = '%s' and is_deleted = 0;",userName);
    if(mysql_query(mysql,query)!=0){
        fprintf(stderr,"查询失败：%s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *result = mysql_store_result(mysql);
    if(result == NULL){
        fprintf(stderr,"结果错误:%s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_ROW row=mysql_fetch_row(result);
    if(row && row[0]){
        printf("得到盐值!\n");
        memcpy(salt,row[0],strlen(row[0]));
    }
    mysql_free_result(result);
    return 0;
}
